package scoreCard.LivestockJudging3C;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import scoreCard.LivestockJudging3C.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;

public class ScoreCalculatorActivity extends Activity {
	 CheckBox checkBox;
	 Spinner qspinner;
	 
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calculator);
		
		String extStorageDirectory = (Environment.getExternalStorageDirectory()+ "/3C/Competition").toString();
		File f = new File(extStorageDirectory);
		String[]CompNames = f.list();

		// Competition
		final AutoCompleteTextView  comptext = (AutoCompleteTextView) findViewById(R.id.scoreCompName);
		ArrayAdapter<String> compadapter = new ArrayAdapter<String>(this, R.layout.list_item, CompNames);
		comptext.setAdapter(compadapter);
		Bundle info = getIntent().getExtras();
		if (info != null) {
			comptext.setText(info.getString("Parent"));
		}

		Spinner spinnerClass = (Spinner) findViewById(R.id.spinnerClass);
		ArrayAdapter<CharSequence> classAdapter = ArrayAdapter.createFromResource(
				this, R.array.spinner_class,
				android.R.layout.simple_spinner_item);
		classAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerClass.setAdapter(classAdapter);
		
		Spinner detailSpinnerClass = (Spinner) findViewById(R.id.detailSpinnerClass);
		ArrayAdapter<CharSequence> detailClassAdapter = ArrayAdapter.createFromResource(
				this, R.array.detail_spinner_class,
				android.R.layout.simple_spinner_item);
		detailClassAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		detailSpinnerClass.setAdapter(detailClassAdapter);
		
		// Official Score Spinners
		final Spinner spinner11 = (Spinner) findViewById(R.id.spinner11);
		ArrayAdapter<CharSequence> adapter11 = ArrayAdapter.createFromResource(
				this, R.array.official_order,
				android.R.layout.simple_spinner_item);
		adapter11
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner11.setAdapter(adapter11);

		final Spinner spinner12 = (Spinner) findViewById(R.id.spinner12);
		ArrayAdapter<CharSequence> adapter12 = ArrayAdapter.createFromResource(
				this, R.array.official_order,
				android.R.layout.simple_spinner_item);
		adapter12
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner12.setAdapter(adapter12);

		final Spinner spinner13 = (Spinner) findViewById(R.id.spinner13);
		ArrayAdapter<CharSequence> adapter13 = ArrayAdapter.createFromResource(
				this, R.array.official_order,
				android.R.layout.simple_spinner_item);
		adapter13
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner13.setAdapter(adapter13);

		final Spinner spinner14 = (Spinner) findViewById(R.id.spinner14);
		ArrayAdapter<CharSequence> adapter14 = ArrayAdapter.createFromResource(
				this, R.array.official_order,
				android.R.layout.simple_spinner_item);
		adapter14
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner14.setAdapter(adapter14);

		// Penalties Cut
		final Spinner spinner31 = (Spinner) findViewById(R.id.spinner31);
		ArrayAdapter<CharSequence> adapter31 = ArrayAdapter.createFromResource(
				this, R.array.penalties_array,
				android.R.layout.simple_spinner_item);
		adapter31
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner31.setAdapter(adapter31);

		final Spinner spinner32 = (Spinner) findViewById(R.id.spinner32);
		ArrayAdapter<CharSequence> adapter32 = ArrayAdapter.createFromResource(
				this, R.array.penalties_array,
				android.R.layout.simple_spinner_item);
		adapter32
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner32.setAdapter(adapter32);

		final Spinner spinner33 = (Spinner) findViewById(R.id.spinner33);
		ArrayAdapter<CharSequence> adapter33 = ArrayAdapter.createFromResource(
				this, R.array.penalties_array,
				android.R.layout.simple_spinner_item);
		adapter33
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner33.setAdapter(adapter33);

		// Personal Score Spinners
		final Spinner spinner21 = (Spinner) findViewById(R.id.spinner21);
		ArrayAdapter<CharSequence> adapter21 = ArrayAdapter.createFromResource(
				this, R.array.personal_order,
				android.R.layout.simple_spinner_item);
		adapter21
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner21.setAdapter(adapter21);

		final Spinner spinner22 = (Spinner) findViewById(R.id.spinner22);
		ArrayAdapter<CharSequence> adapter22 = ArrayAdapter.createFromResource(
				this, R.array.personal_order,
				android.R.layout.simple_spinner_item);
		adapter22
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner22.setAdapter(adapter22);

		final Spinner spinner23 = (Spinner) findViewById(R.id.spinner23);
		ArrayAdapter<CharSequence> adapter23 = ArrayAdapter.createFromResource(
				this, R.array.personal_order,
				android.R.layout.simple_spinner_item);
		adapter23
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner23.setAdapter(adapter23);

		final Spinner spinner24 = (Spinner) findViewById(R.id.spinner24);
		ArrayAdapter<CharSequence> adapter24 = ArrayAdapter.createFromResource(
				this, R.array.personal_order,
				android.R.layout.simple_spinner_item);
		adapter24
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner24.setAdapter(adapter24);
		
		// Question Score
		checkBox = (CheckBox) findViewById(R.id.checkbox);
		
		qspinner = (Spinner) findViewById(R.id.qspinner);
		ArrayAdapter<CharSequence> qadapter = ArrayAdapter.createFromResource(
				this, R.array.q_score,
				android.R.layout.simple_spinner_item);
		qadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		qspinner.setAdapter(qadapter);
		qspinner.setVisibility(View.INVISIBLE);
		
		checkBox.setOnClickListener(new CheckBox.OnClickListener() {
	          public void onClick(View v){
	                if (checkBox.isChecked()) {
	                	// Show Spinner
	                    qspinner.setVisibility(View.VISIBLE);
	                }
	                else
	                {
	                	// Hide Spinner
	                	qspinner.setVisibility(View.INVISIBLE);
	                }
	          }
	    });

		// Calculate Button
		Button calculateButton = (Button) findViewById(R.id.calculateButton);
		calculateButton.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {

				populateArraysFromUI(spinner11.getSelectedItem(),
						spinner12.getSelectedItem(),
						spinner13.getSelectedItem(),
						spinner14.getSelectedItem(),
						spinner31.getSelectedItem(),
						spinner32.getSelectedItem(),
						spinner33.getSelectedItem(),
						spinner21.getSelectedItem(),
						spinner22.getSelectedItem(),
						spinner23.getSelectedItem(),
						spinner24.getSelectedItem());

				if (checkErrors()) {
					showDialog(ERROR_DIALOG);
				} else {
					ScoringCalculator sc = new ScoringCalculator(
							Official_Array, Official_Cuts, Personal_Array);
					total = sc.calculateScore();
					showDialog(SCORE_DIALOG);
				}

			}
		});
	}

	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
		case (SCORE_DIALOG): {
			AlertDialog.Builder scoreDialog = new AlertDialog.Builder(this);
			scoreDialog.setMessage("Score: ");
			scoreDialog.setPositiveButton("Save",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							String compName = ((EditText) findViewById(R.id.scoreCompName)).getText().toString();
							String classDesc = ((EditText) findViewById(R.id.classDesc)).getText().toString();
							if (classDesc != null && !classDesc.equals(""))
							{
								classDesc += " ";
							}
							Spinner classNameSpinner = (Spinner) findViewById(R.id.spinnerClass);
							Spinner detailNameSpinner = (Spinner)findViewById(R.id.detailSpinnerClass);
							String detailClass = detailNameSpinner.getSelectedItem().toString();
							String className = classNameSpinner.getSelectedItem().toString();
							if (className != null && !className.equals(""))
							{
								detailClass += " ";
							}
							if (compName != null && !compName.equals("")) {
								SaveFile save = new SaveFile();
								save.SaveScore(compName, classDesc + detailClass + className, total, false, true);
								// Get Question Score
								if (checkBox.isChecked()) {
									try {
										int qscore = Integer.parseInt((qspinner.getSelectedItem()).toString());
										save.SaveScore(compName, classDesc + detailClass + className, qscore, true, false);
									} catch (NumberFormatException ex) {
										ex.printStackTrace();
									}
									
								}
								Intent intent = new Intent(ScoreCalculatorActivity.this, HistoryActivity.class);
					    		Bundle info  = new Bundle();
					    		info.putString("Competition", compName);
					    		info.putString("Class", classDesc + detailClass + className);
					    		intent.putExtras(info);
					    		startActivity(intent);
							} else {
								showDialog(SAVE_ERROR_DIALOG);
							}
						}
					});
			scoreDialog.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			return scoreDialog.create();
		}
		case (ERROR_DIALOG): {
			AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
			errorDialog.setMessage("Error!");
			errorDialog.setNegativeButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			return errorDialog.create();
		}
		case (SAVE_ERROR_DIALOG): {
			AlertDialog.Builder saveDialog = new AlertDialog.Builder(this);
			saveDialog.setMessage("You must enter a competition name before saving.");
			saveDialog.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});
			return saveDialog.create();
		}
		}
		return null;
	}

	@Override
	public void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case (SCORE_DIALOG): {
			AlertDialog scoreDialog = (AlertDialog) dialog;
			CheckBox qCheck = (CheckBox) findViewById(R.id.checkbox);
			if (qCheck.isChecked()) {
				try {
					Spinner qSpinner = (Spinner) findViewById(R.id.qspinner);
					int questionScore = Integer.parseInt(qSpinner.getSelectedItem().toString());
					scoreDialog.setMessage("Placing Score: " + total + "\nQuestion Score: " + questionScore);
				} catch (NumberFormatException ex) {
					scoreDialog.setMessage("Placing Score: " + total);
					ex.printStackTrace();
				}
				
			} else 
			{
				scoreDialog.setMessage("Placing Score: " + total);
			}
			
			break;
		}
		case (ERROR_DIALOG): {
			AlertDialog errorDialog = (AlertDialog) dialog;
			errorDialog.setMessage(errorMessage);
			break;
		}
		}
	}

	private void populateArraysFromUI(Object selectedItem,
			Object selectedItem2, Object selectedItem3, Object selectedItem4,
			Object selectedItem5, Object selectedItem6, Object selectedItem7,
			Object selectedItem8, Object selectedItem9, Object selectedItem10,
			Object selectedItem11) {
		// Load official score into array
		if (!selectedItem.toString().equals("")
				&& !selectedItem2.toString().equals("")
				&& !selectedItem3.toString().equals("")
				&& !selectedItem4.toString().equals("")
				&& !selectedItem5.toString().equals("")
				&& !selectedItem6.toString().equals("")
				&& !selectedItem7.toString().equals("")
				&& !selectedItem8.toString().equals("")
				&& !selectedItem9.toString().equals("")
				&& !selectedItem10.toString().equals("")
				&& !selectedItem11.toString().equals("")) {

			int official1 = Integer.parseInt(selectedItem.toString());
			int official2 = Integer.parseInt(selectedItem2.toString());
			int official3 = Integer.parseInt(selectedItem3.toString());
			int official4 = Integer.parseInt(selectedItem4.toString());

			Official_Array[0] = official1;
			Official_Array[1] = official2;
			Official_Array[2] = official3;
			Official_Array[3] = official4;

			// Load cuts into array
			int cut1 = Integer.parseInt(selectedItem5.toString());
			int cut2 = Integer.parseInt(selectedItem6.toString());
			int cut3 = Integer.parseInt(selectedItem7.toString());

			Official_Cuts[0] = cut1;
			Official_Cuts[1] = cut2;
			Official_Cuts[2] = cut3;

			// Load personal score into array
			int personal1 = Integer.parseInt(selectedItem8.toString());
			int personal2 = Integer.parseInt(selectedItem9.toString());
			int personal3 = Integer.parseInt(selectedItem10.toString());
			int personal4 = Integer.parseInt(selectedItem11.toString());

			Personal_Array[0] = personal1;
			Personal_Array[1] = personal2;
			Personal_Array[2] = personal3;
			Personal_Array[3] = personal4;
		} else {
			Personal_Array[0] = 0;
			Personal_Array[1] = 0;
			Personal_Array[2] = 0;
			Personal_Array[3] = 0;

			Official_Cuts[0] = 0;
			Official_Cuts[1] = 0;
			Official_Cuts[2] = 0;

			Official_Array[0] = 0;
			Official_Array[1] = 0;
			Official_Array[2] = 0;
			Official_Array[3] = 0;
		}
	}

	private boolean checkErrors() {
		int penaltyTotal = Official_Cuts[0] + Official_Cuts[1]
				+ Official_Cuts[2];
		if (penaltyTotal > 15) {
			errorMessage = "Error! The total of the three cuts cannot exceed 15 points.";
			return true;
		} else if (penaltyTotal == 15 && Official_Cuts[1] > 5) {
			errorMessage = "Error! If the total of the three cuts is 15 points, the middle cut cannot be more than 5 points.";
			return true;
		} else if (penaltyTotal == 14 && Official_Cuts[1] > 8) {
			errorMessage = "Error! If the total of the three cuts is 14 points, the middle cut cannot be more than 8 points.";
			return true;
		}

		Set<Integer> officialSet = new HashSet<Integer>();
		for (int item : Official_Array) {
			if (item == 0) {
				errorMessage = "Error! The numbers in the official placing, penalties, and personal placing cannot be left blank.";
				return true;
			} else if (officialSet.contains(item)) {
				errorMessage = "Error! The number " + item
						+ " was duplicated in the official placing.";
				return true;
			} else {
				officialSet.add(item);
			}
		}
		Set<Integer> personalSet = new HashSet<Integer>();
		for (int item : Personal_Array) {
			if (personalSet.contains(item)) {
				errorMessage = "Error! The number " + item
						+ " was duplicated in the personal placing.";
				return true;
			} else {
				personalSet.add(item);
			}
		}
		return false;
	}

	static final private int SCORE_DIALOG = 1;
	static final private int ERROR_DIALOG = 2;
	static final private int SAVE_ERROR_DIALOG = 3;
	private int total;
	private final int[] Official_Array = new int[4];
	private final int[] Official_Cuts = new int[3];
	private final int[] Personal_Array = new int[4];
	private String errorMessage;
}
